<?php
/**
 * File: Sdk.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/18 14:44
 */


namespace Common\Extend\DingTalk\Client;


use Common\Extend\Helper\Exception;

require_once('sdk/TopSdk.php');

class SdkClient
{
    protected $client;
    protected $token;
    private static $_instance;

    public function __construct()
    {
        $this->client = new \DingTalkClient;
        //返回格式
        $this->client->format = 'json';
    }

    public static function getInstance()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function setToken($token)
    {
        if (!isset($this->token)) {
            $this->token = $token;
        }

    }

    public function req($name)
    {
        $name = '\\' . $name;
        return (new $name);
    }

    public function run($req)
    {
        $response = $this->client->execute($req, $this->token);
        return $this->response($response);

    }

    public function response($response)
    {
        //std to array
        $data = json_decode(json_encode($response), true);
        //sdk报错
        if (isset($data['code']) && $data['code'] != 0) {
            throw new Exception($data['msg'], $data['code']);
        }
        //接口入参报错
        if (isset($data['result']['ding_open_errcode']) && $data['result']['ding_open_errcode'] != 0) {
            throw new Exception($data['result']['error_msg'], $data['result']['ding_open_errcode']);
        }

        return $data;

    }
}